<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset='UTF-8'>  
<link rel='stylesheet' href='css/style1.css' /> 
<title>Start Battle: Choose player you want to play with</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function(){
  var users = null;
  
  $.fn.loadPlayers = function() {
    var filter = $("[name=findthis]").val();
    var fitsFilter = function(user) {
     return user.name.toLowerCase().indexOf(filter.toLowerCase()) != -1;
    };
    
    this.html("");
    // for each user that fits filter
    for (var i = 0; i < users.length; i++) if (fitsFilter(users[i])) {
      var el;
      if (users[i].available == "true") {
        // available for challenge -> post to main window on click
      	el = $("<li \>").attr("class", "available");
      	el.on("click", users[i] ,function(e) {choose(e.data.id, e.data.name);});
      }
      else 
        el = $("<li \>").attr("class", "unavailable");
      el.text(users[i].name);
      this.append(el);
    }
  } 

  function getAll() {
    $.get("Chat?userlistUpdates=true", updateUsers);
  }
  
  function updateUsers(resp) {
    //parse response
    if (resp != "") {
      users = $.parseJSON(resp);
      console.log(users);
      $("#playerlist").loadPlayers();
    }
    getAll();
  }
  
  $.get("Chat?userlistUpdates=now", updateUsers);
});

function choose(id, name) {
  console.log("Chose: "+id+", "+name);
  window.opener.postMessage(id+"&"+name, '*');
}

function filterList() {
  console.log("filter: " + $("[name=findthis]").val());
  $("#playerlist").loadPlayers();
}
</script>


</head>
<body>
<form name="form1" onsubmit="filterList(); return false" style="text-align:center">
  <input type="text" name="findthis" size="15" title="Search box" 
    onkeypress="return event.keyCode != 13;"
    onkeydown="setTimeout(filterList, 0);"> 
<!--   <input type="submit" value="Find" ACCESSKEY="s"> -->
</form>
  <h1>Online players:</h1>
  <ul id="playerlist">

  </ul>
</body>
</html>
